<template>
  <div id="EquipmentDetailsPage">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">设备详情</span>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="equipment-detail" v-if="equipmentInfo">
        <div class="left-content">
          <div class="equipment-image">
            <img
              :src="
                equipmentInfo.photoList[0]?.url ||
                require('@/assets/images/defaultDevice.png')
              "
              alt="设备图片"
              class="equipment-photo"
            />
          </div>
        </div>
        <div class="right-content">
          <div class="header-row">
            <div class="title-section">
              <span class="equipment-name">{{ equipmentInfo.name }}</span>
              <el-button size="small" class="type-btn">{{
                equipmentInfo.typeInfo?.name
              }}</el-button>
              <div class="status-tag" :class="equipmentInfo.status">
                {{ statusMap[equipmentInfo.status] }}
              </div>
            </div>
          </div>

          <div class="sn-model-row">
            <span class="label">序列号: {{ equipmentInfo.code }}</span>
            <span class="separator">|</span>
            <span class="label">型号: {{ equipmentInfo.model }}</span>
          </div>

          <div class="info-table">
            <div class="info-row">
              <div class="info-item">
                <span class="label">采购时间</span>
                <span class="value">{{
                  formatDate(equipmentInfo.purchaseDate || 0)
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">投运时间</span>
                <span class="value">{{
                  formatDate(equipmentInfo.deliveryDate || 0)
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">使用年限</span>
                <span class="value">{{ equipmentInfo.useYears }}年</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <span class="label">所属院系</span>
                <span class="value">{{ ogaMap[equipmentInfo.belong] }}</span>
              </div>
              <div class="info-item">
                <span class="label">当前位置</span>
                <span class="value">{{ equipmentInfo.location }}</span>
              </div>
              <div class="info-item">
                <span class="label">当前责任人</span>
                <span class="value">{{
                  equipmentInfo.chargeUserInfo?.name || "--"
                }}</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <span class="label">设备价值</span>
                <span class="value">{{
                  formatCurrency(equipmentInfo.purchasePrice || 0)
                }}</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <span class="label">备注1</span>
                <span class="value">{{
                  equipmentInfo.description1 || "--"
                }}</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <span class="label">备注2</span>
                <span class="value">{{
                  equipmentInfo.description2 || "--"
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="loading-wrapper">
        <div>加载中...</div>
      </div>

      <!-- 设备图片管理 -->
      <div class="equipment-attachment-wrapper">
        <EquipmentAttachment :equipmentId="equipmentId" :isLook="true" />
      </div>
      <!-- 设备文档管理 -->

      <div class="maintenance-plan-wrapper">
        <MaintenancePlan :isLook="true" />
      </div>
      <div class="repair-work-order-wrapper">
        <RepairWorkOrder :userList="userList" :isLook="true" />
      </div>
      <div class="other-info-wrapper">
        <div class="contact-wrapper">
          <Contact :isLook="true" />
        </div>
        <div class="contract-wrapper">
          <Contract :isLook="true" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import Contact from "@/components/Contact.vue";
import Contract from "@/components/Contract.vue";
import MaintenancePlan from "@/components/MaintenancePlan.vue";
import RepairWorkOrder from "@/components/RepairWorkOrder.vue";
import EquipmentAttachment from "@/components/EquipmentAttachment.vue";
import { getEquipmentByIdAPI, typesAPI } from "@/api/service/equipmentManage";
import { EquipmentType } from "@/api/types/equipment";
import { getOgaListAPI, OgaType } from "@/api/service/oga";
import { getUserListAPI, UserType, GetUserListType } from "@/api/service/user";
import { formatCurrency, formatDate } from "@/assets/js/utils";

const route = useRoute();
const router = useRouter();
const equipmentId = route.query.id as string;

// 获取用户列表
const userList = ref<UserType[]>([]);
const userListLoading = ref(false);
const userListQuery = ref<GetUserListType>({
  page: 1,
  size: 1000,
  name: "",
  ogaCode: "",
});
function getUserList() {
  if (userListLoading.value) return;
  userListLoading.value = true;
  getUserListAPI({
    name: userListQuery.value.name,
    ogaCode: userListQuery.value.ogaCode,
    page: userListQuery.value.page,
    size: userListQuery.value.size,
  })
    .then((res: any) => {
      userList.value = res.content;
    })
    .finally(() => {
      userListLoading.value = false;
    });
}
getUserList();

// 获取设备类型列表
const equipmentTypeList = ref<EquipmentType[]>([]);
const equipmentTypeListLoading = ref(false);
function getEquipmentTypeList() {
  if (equipmentTypeListLoading.value) return;
  equipmentTypeListLoading.value = true;
  typesAPI()
    .then((res: any) => {
      equipmentTypeList.value = res.deviceTypes || [];
    })
    .catch(() => {
      ElMessage.error("获取设备类型列表失败");
    })
    .finally(() => {
      equipmentTypeListLoading.value = false;
    });
}
getEquipmentTypeList();

// 获取组织结构列表
const ogaList = ref<OgaType[]>([]);
const ogaMap = ref<Record<string, string>>({});
const ogaListApiLoading = ref(false);

// 加载组织列表
const loadOgaList = async () => {
  try {
    if (ogaListApiLoading.value) return;
    ogaListApiLoading.value = true;

    const response = await getOgaListAPI();
    const result = response as any as OgaType[];
    if (result) {
      ogaList.value = result || [];
      ogaList.value?.forEach((item) => {
        ogaMap.value[item.code] = item.name;
      });
    }
  } catch (error) {
    ElMessage.error("获取组织列表失败");
    console.error("Load oga list error:", error);
  } finally {
    ogaListApiLoading.value = false;
  }
};
loadOgaList();

// 设备基本信息
const statusMap = ref<Record<string, string>>({
  IDLE: "空闲中",
  RESERVEING: "预约中",
  IN_USE: "使用中",
  REPAIRING: "维护中",
  DAMAGED: "损坏",
  SCRAPPED: "报废",
});
const equipmentInfo = ref<any>();

// API调用保护状态
const equipmentInfoApiLoading = ref(false);

function getEquipmentInfo() {
  // 防止并发调用
  if (equipmentInfoApiLoading.value) return;

  equipmentInfoApiLoading.value = true;

  getEquipmentByIdAPI(equipmentId)
    .then((_data: any) => {
      const data = _data as EquipmentType;
      equipmentInfo.value = data;
    })
    .catch(() => {
      ElMessage.error("获取设备详情失败");
    })
    .finally(() => {
      equipmentInfoApiLoading.value = false;
    });
}
getEquipmentInfo();
// 返回
function backHandle() {
  router.back();
}
</script>

<style scoped lang="scss">
#EquipmentDetailsPage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 1rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
  padding: 1.5rem;
  background-color: #fff;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
  }
  .back-btn {
    display: flex;
    align-items: center;
    padding: 0.5rem 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 2rem;
  overflow: auto;

  .equipment-detail {
    display: flex;
    gap: 2rem;
    border-radius: 8px;
    padding: 2rem 2rem 1rem 2rem;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .left-content {
    width: 300px;
    .equipment-image {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
      }
    }
  }

  .right-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 1rem;
    margin-left: 1rem;
    .header-row {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .title-section {
        display: flex;
        align-items: center;
        gap: 1rem;

        .equipment-name {
          font-size: $font-size-block-title;
          font-weight: 500;
          color: #fff;
          font-family: "Alibaba-PuHuiTi-Medium";
        }

        .type-btn {
          background-color: #ba7bfb;
          color: #fff;
          border-radius: 1rem;
          border: none;
        }

        .status-tag {
          padding: 0.25rem 1rem;
          border-radius: 1rem;
          font-size: $font-size-tips;
          font-weight: 500;

          &.IDLE {
            background-color: #fff;
            color: $text-color-regular;
          }
          &.RESERVEING {
            background-color: $color_warning;
            color: $text-color-regular;
          }

          &.DAMAGED {
            background-color: $color_danger;
            color: $text-color-regular;
          }
          &.IN_USE {
            background-color: $color_success;
            color: $text-color-regular;
          }
          &.REPAIRING {
            background-color: $color_warning;
            color: $text-color-regular;
          }
          &.SCRAPPED {
            background-color: $color_danger;
            color: $text-color-regular;
          }
        }
      }
    }

    .sn-model-row {
      font-size: $font-size-tips;
      color: $text-color-regular;
      margin-bottom: 1rem;

      .separator {
        color: $text-color-regular;
        margin: 0 0.5rem;
      }
    }

    .info-table {
      display: flex;
      flex-direction: column;
      gap: 0.5rem;

      .info-row {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        margin-bottom: 1rem;
      }

      .info-item {
        display: flex;
        align-items: center;
        min-width: 180px;

        .label {
          display: inline-block;
          width: 80px;
          color: $text-color-regular;
          font-size: $font-size-base;
          text-align: left;
          flex-shrink: 0;
        }

        .value {
          color: $text-color-regular;
          font-size: $font-size-tips;
          margin-left: 0.5rem;
        }
      }
    }
  }

  .loading-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: $text-color-secondary;
    font-size: $font-size-base;
  }

  .equipment-attachment-wrapper {
    margin-top: 2rem;
    border: 1px solid $border-color-primary;
    border-radius: 8px;
    padding: 0 0 2rem 0;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    // background-color: $text-color-placeholder;
  }
  .maintenance-plan-wrapper {
    margin-top: 2rem;
    border: 1px solid $border-color-primary;
    border-radius: 8px;
    padding: 0 0 2rem 0;
    background-color: #fff;
    // background-color: $text-color-placeholder;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
  .repair-work-order-wrapper {
    margin-top: 2rem;
    border: 1px solid $border-color-primary;
    border-radius: 8px;
    padding: 0 0 2rem 0;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    // background-color: $text-color-placeholder;
  }
  .other-info-wrapper {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 3rem;
    margin-top: 2rem;
    .contact-wrapper {
      border: 1px solid $border-color-primary;
      border-radius: 8px;
      padding: 0 0 2rem 0;
      background-color: #fff;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      // background-color: $text-color-placeholder;
    }
    .contract-wrapper {
      border: 1px solid $border-color-primary;
      border-radius: 8px;
      padding: 0 0 2rem 0;
      background-color: #fff;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      // background-color: $text-color-placeholder;
    }
  }
}

:deep(.el-input__inner) {
  text-align: left !important;
}
</style>
